﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Utilities;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Security.Claims;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Ecommerce.Models;
using Library;

namespace Ecommerce
{
    public class EmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
    }

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }

    public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
        public ApplicationUserStore(UserManagerDbContext context)
            : base(context)
        {
        }
    }

    public class CulturePasswordValidator : PasswordValidator
    {
        public override Task<IdentityResult> ValidateAsync(string item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            var errors = new List<string>();
            if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength)
            {
                errors.Add(string.Format(NOWCulture.GetString("{0} must be at least {1} characters."), NOWCulture.GetString("Password"), RequiredLength));
            }
            if (RequireNonLetterOrDigit && item.All(IsLetterOrDigit))
            {
                errors.Add(NOWCulture.GetString("Passwords must have at least one non letter or digit character."));
            }
            if (RequireDigit && item.All(c => !IsDigit(c)))
            {
                errors.Add(NOWCulture.GetString("Passwords must have at least one digit character."));
            }
            if (RequireLowercase && item.All(c => !IsLower(c)))
            {
                errors.Add(NOWCulture.GetString("Passwords must have at least one lowercase ('a'-'z')."));
            }
            if (RequireUppercase && item.All(c => !IsUpper(c)))
            {
                errors.Add(NOWCulture.GetString("Passwords must have at least one uppercase ('A'-'Z')."));
            }
            if (errors.Count == 0)
            {
                return Task.FromResult(IdentityResult.Success);
            }
            return Task.FromResult(IdentityResult.Failed(String.Join(" ", errors)));
        }
    }

    public class CultureUserValidator : UserValidator<ApplicationUser>
    {
        public bool UsingEmailAsUsername { get; set; }

        private UserManager<ApplicationUser, string> Manager { get; set; }

        public CultureUserValidator(UserManager<ApplicationUser, string> manager)
            : base(manager)
        {
            Manager = manager;
        }

        public override async Task<IdentityResult> ValidateAsync(ApplicationUser item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            var errors = new List<string>();
            if (!UsingEmailAsUsername)
            {
                await ValidateUserName(item, errors);
            }
            if (RequireUniqueEmail)
            {
                await ValidateEmail(item, errors);
            }
            if (errors.Count > 0)
            {
                return IdentityResult.Failed(errors.ToArray());
            }
            return IdentityResult.Success;
        }

        private async Task ValidateUserName(ApplicationUser user, List<string> errors)
        {
            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                errors.Add(string.Format(NOWCulture.GetString("{0} is required."), NOWCulture.GetString("User name")));
            }
            else if (AllowOnlyAlphanumericUserNames && !Regex.IsMatch(user.UserName, @"^[A-Za-z0-9@_\.]+$"))
            {
                // If any characters are not letters or digits, its an illegal user name
                errors.Add(NOWCulture.GetString("Only allow 'a'-'z', 'A'-'Z', '1'-'9', '@', '_' characters in user name."));
            }
            else
            {
                var owner = await Manager.FindByNameAsync(user.UserName);
                if (owner != null && !EqualityComparer<string>.Default.Equals(owner.Id, user.Id))
                {
                    errors.Add(string.Format(NOWCulture.GetString("{0} '{1}' already exists."), NOWCulture.GetString("User name"), user.UserName));
                }
            }
        }

        // make sure email is not empty, valid, and unique
        private async Task ValidateEmail(ApplicationUser user, List<string> errors)
        {
            string email = user.Email;
            if (string.IsNullOrWhiteSpace(email))
            {
                errors.Add(string.Format(NOWCulture.GetString("{0} is required."), NOWCulture.GetString("Email")));
                return;
            }
            try
            {
                var m = new MailAddress(email);
            }
            catch (FormatException)
            {
                errors.Add(string.Format(NOWCulture.GetString("{0} '{1}' is invalid."), NOWCulture.GetString("Email"), email));
                return;
            }
            var owner = await Manager.FindByEmailAsync(email);
            if (owner != null && !EqualityComparer<string>.Default.Equals(owner.Id, user.Id))
            {
                errors.Add(string.Format(NOWCulture.GetString("{0} '{1}' already exists."), NOWCulture.GetString("Email"), email));
            }
        }
    }

    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser, string>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<UserManagerDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new CultureUserValidator(manager)
            {
                UsingEmailAsUsername = true,
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new CulturePasswordValidator
            {
                RequiredLength = 8,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = NOWCulture.GetString("Your security code is {0}")
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = NOWCulture.GetString("Security Code"),
                BodyFormat = NOWCulture.GetString("Your security code is {0}")
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }

        public async Task<IdentityResult> ChangePasswordAsync(string userId, string newPassword)
        {
            var user = await FindByIdAsync(userId).WithCurrentCulture();
            if (user == null)
            {
                throw new InvalidOperationException("Not found user by ID " + userId);
            }

            var result = await RemovePasswordAsync(userId);
            if (!result.Succeeded)
            {
                return result;
            }          
            result = await AddPasswordAsync(userId, newPassword);
            if (!result.Succeeded)
            {
                return result;
            }
            return await UpdateAsync(user);
        }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }

    public class ApplicationRoleManager : RoleManager<ApplicationRole>
    {
        public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
            : base(roleStore)
        {
        }

        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<UserManagerDbContext>()));
        }
    }
}
